package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.utils.RedisTemplateUtil;
import com.example.utils.StringRedisTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: RedisController
 * @Author: mingtian
 * @CreateDate: 2019/11/15 16:50
 * @Version: 1.0
 */
@RestController
public class RedisController {

    @Autowired
    private StringRedisTemplateUtil stringRedisTemplateUtil;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Resource
    private UserMapper userMapper;

    @GetMapping("/addUserString")
    public String add(User user) {
        if (StringUtils.isEmpty(user.getUserId())) {
            return "id can not be empty!";
        }
        if (StringUtils.isEmpty(user.getUserName())) {
            return "name can not be empty!";
        }

        String s = JSONObject.toJSONString(user);

        stringRedisTemplateUtil.add(user.getUserId(), s, null);
        return "addUser Success";
    }

    @GetMapping("/getUserString")
    public String get(String id) {
        if (StringUtils.isEmpty(id)) {
            return "key can not be empty!";
        }
        String value = stringRedisTemplateUtil.getByKey(id);
        return value;
    }


    @GetMapping("/addUser")
    public String addUser(User user) {
        if (StringUtils.isEmpty(user.getUserId())) {
            return "id can not be empty!";
        }
        if (StringUtils.isEmpty(user.getUserName())) {
            return "name can not be empty!";
        }

        redisTemplateUtil.add(user.getUserId(), user, null);
        return "addUser Success";
    }

    @GetMapping("/getUser")
    public User getUser(String id) {
        User user = (User) redisTemplateUtil.getByKey(id);
        return user;
    }

    @GetMapping("/getUserList")
    @Cacheable(cacheNames = "user", key = "'getUserList'")
    public List<User> getUserList() {
        List<User> userList = userMapper.getUserList();
        return userList;
    }

    @GetMapping("/getUserByUserId")
    @Cacheable(cacheNames = "user", key = "'getUserByUserId'")
    public User getUserByUserId(String userId) {
        User user = userMapper.getUserByUserId(userId);
        return user;
    }

    @GetMapping("/getHashCode")
    public String getHashCode(String code) {
        if (StringUtils.isEmpty(code)) {
            return "code can not be empty!";
        }
        return code.hashCode() + "";
    }

}
